﻿using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.Traceability;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.Traceability
{
    /// <summary>
    /// 溯源信息删除
    /// </summary>
    public class DelTraceabilityCommandHandle:IRequestHandler<DelTraceabilityCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Traceability_Management> TraceabilityDal;

        public DelTraceabilityCommandHandle(IBaseRepository<Traceability_Management> traceabilityDal)
        {
            TraceabilityDal = traceabilityDal;
        }

        public Task<APIResult<int>> Handle(DelTraceabilityCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var trace = TraceabilityDal.GetValue(request.Id).Result;
            trace.IsDeleted = true;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = TraceabilityDal.Update(trace).Result;
                tran.Complete();
            }


            if (r > 0)
            {
                result.Code = StateCode.Ok;
                result.Message = "删除成功";
                return Task.FromResult(result);
            }
            else
            {
                result.Code = StateCode.Faile;
                result.Message = "删除失败";
                return Task.FromResult(result);
            }

        }

    }
}
